#include "StdAfx.h"
#include "ExceptionHandler.h"
#include "M2Info.h"

#pragma comment(lib, "d3dx9.lib")
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "psapi.lib")

D3DXMATRIX matID;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	ExceptionHandler::attachToProcess();

	CreateMutex(NULL, TRUE, "YIASDX_UPDATE_MUTEX");
	ui32 lastErr = GetLastError();
	if(lastErr == ERROR_ALREADY_EXISTS || lastErr == ERROR_ACCESS_DENIED)
	{
		MessageBox(0, "Currently the updater for YiasDX is running. Please do not run YiasDX during this time!", "Error", MB_OK | MB_ICONERROR);
		return 0;
	}

	CreateMutex(NULL, TRUE, "YIASDX_MUTEX");
	lastErr = GetLastError();
	if(lastErr == ERROR_ALREADY_EXISTS || lastErr == ERROR_ACCESS_DENIED)
	{
		MessageBox(0, "YiasDX is already running! Please do not run multiple copies of the program!", "Error", MB_OK | MB_ICONERROR);
		return 0;
	}

	srand(time(0));
	Math::Init();
	try
	{
		LoadLibrary("Riched20.dll");
		Log::Print("Loading YiasEdit DX build from %s (%s)\n\n", __DATE__, __TIME__);
		new SplashScreen();
		ConfigFile::LoadConfigs();
		sSplash.Show();
		D3DXMatrixIdentity(&matID);
		new CMpqHandler();
		sMpqHandler.Init();

		new LocaleMgr();
		new CTextureHandler();
		
		new CWindow(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));

		sSplash.Hide();
		sWindow.BeginShow();
	}
	catch(StartupException& e)
	{
		MessageBox(0, e.szBody.c_str(), e.szTitle.c_str(), MB_OK);
	}
	return 0;
}